package com.test.concurrency;

import java.util.concurrent.TimeUnit;

class NeedsCleanup {
	private final int id;

	public NeedsCleanup(int ident) {
		id = ident;
		System.out.println("NeedsCleanUp " + id);
	}

	public void cleanup() {
		System.out.println("Cleaning up " + id);
	}
}

class Blocked3 implements Runnable {
	private volatile double d = 0.0;

	@Override
	public void run() {
		try {
			while (!Thread.interrupted()) {
				// point1
				NeedsCleanup n1 = new NeedsCleanup(1);
				// start try-finally immediately after definition
				// of n1. to guarantee proper cleanup of n1:
				try {
					System.out.println("Sleeping");
					TimeUnit.SECONDS.sleep(1);
					// point2
					NeedsCleanup n2 = new NeedsCleanup(2);
					// Guarantee proper cleanup of n2:
					try {
						System.out.println("Calculating");
						// a time-consuming ,non-blocking operation:
						for (int i = 1; i < 2500000; i++) {
							d = d + (Math.E + Math.PI) / d;
						}
						System.out.println("Finished time-consuming operation");
					} finally {
						n2.cleanup();
					}
				} finally {
					n1.cleanup();
				}
			}
			System.out.println("exiting via while() test");

		} catch (Exception e) {
			System.out.println("Exiting via InterruptedException");
		}

	}

}

/**
 * a class designed to respond to an interrupt() must establish a policy to
 * ensure that it will remain in a consistent state,this gennerally means that
 * the creation of all objects that require cleanup must be followed by
 * try-finnally clauses so that cleanup will occur regardless of how the run
 * loop exits
 * 
 * @author Administrator
 * 
 */
public class InterruptingIdiom {
	public static void main(String[] args) throws InterruptedException {
		Thread t = new Thread(new Blocked3());
		t.start();
		TimeUnit.MILLISECONDS.sleep(1100);
		t.interrupt();
	}
}
